/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * ShowBorrowsDialog.java
 *
 * Created on 21.5.2011, 9:59:03
 */
package GUI;

import Model.BorrowManagerImpl;
import Model.Client;
import Model.Medium;
import Model.MediumManagerImpl;
import java.awt.Frame;
import java.sql.SQLException;
import java.util.List;
import java.util.concurrent.ExecutionException;
import javax.sql.DataSource;

import javax.swing.JOptionPane;
import javax.swing.SwingWorker;

/**
 *
 * @author KoBE
 */
public class ShowBorrowsDialog extends javax.swing.JDialog {

    private Frame parent = null;
    private Client client = null;
    
    private LoadBorrowsSwingWorker loadBorrowsSwingWorker;
    private MainFrame clientManagerFrame;
    private BorrowManagerImpl borrowManager = new BorrowManagerImpl();
    
    MediumTableModel mediumModel;
    
    MediumManagerImpl mediumManager = new MediumManagerImpl();    
    
    public ShowBorrowsDialog(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        this.parent = parent;
        
        initComponents();    
        }
    /** Creates new form ShowBorrowsDialog */
    public ShowBorrowsDialog(java.awt.Frame parent, boolean modal, Client client) {
        super(parent, modal);
        this.parent = parent;
        this.client = client;
        
        clientManagerFrame = (MainFrame) parent;
        mediumManager = clientManagerFrame.getMediumManager();
        
        initComponents();
        mediumModel = (MediumTableModel) borrowedMediumsTable.getModel();
        loadBorrowsSwingWorker = new LoadBorrowsSwingWorker();
        loadBorrowsSwingWorker.execute();    
    }
    
    public void setBorrows(Client client) {
        this.client = client;
       // MediumManagerImpl mediumManager = new MediumManagerImpl();        
    }
     
     
    
    private class LoadBorrowsSwingWorker extends SwingWorker<List<Medium>,Void> {

        private String searchString = null;
        
        @Override    
        protected List<Medium> doInBackground() throws Exception {
            
            try {
                DataSource ds = MainFrame.prepareDataSource();
                borrowManager.setDataSource(ds);
                List<Medium> mediums;                
                
                mediums = (List<Medium>)borrowManager.getMediumsBorrovedByClient(client);
                
                return mediums;
//                
//                }
            } catch (SQLException ex) {
                throw new RuntimeException("DB Error",ex);
            }
        }
        
        @Override    
        protected void done() {
            try {
                //jTextArea.append("Result is: " + get() + "\n");
                List<Medium> mediums = get();
                mediumModel.removeAll();
            
                for(Medium m : mediums) {
                    mediumModel.addMedium(m);
                }
                if (mediums.isEmpty()){
                    jButton2.setEnabled(false);
                }
            
            } catch (ExecutionException ex) {
                JOptionPane.showMessageDialog(null, "Error: " + ex);
            } catch (InterruptedException ex) {
                // K tomuto by v tomto případě nemělo nikdy dojít (viz níže)
                throw new RuntimeException("Operation interrupted (this should never happen)",ex);
            }
        }  
        
        public void setSearchString(String s) {
            this.searchString = s;
        }
    }
    
    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        borrowedMediumsTable = new javax.swing.JTable();
        textLabel = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        java.util.ResourceBundle bundle = java.util.ResourceBundle.getBundle("i18n/texts"); // NOI18N
        setTitle(bundle.getString("Add Client/Edit Client")); // NOI18N
        setBounds(new java.awt.Rectangle(300, 200, 0, 0));

        jScrollPane1.setPreferredSize(new java.awt.Dimension(600, 300));

        borrowedMediumsTable.setModel(new MediumTableModel());
        jScrollPane1.setViewportView(borrowedMediumsTable);

        textLabel.setText(bundle.getString("borrowsFromClient")); // NOI18N

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14));
        jLabel1.setText(client.getName());

        jButton1.setText(bundle.getString("close")); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jButton2.setText(bundle.getString("returnMedium")); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(textLabel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jButton2)
                        .addGap(33, 33, 33)
                        .addComponent(jButton1)))
                .addContainerGap(404, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 611, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 263, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap())
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(41, 41, 41)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 227, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(63, Short.MAX_VALUE)))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        if (borrowedMediumsTable.getSelectedRowCount() != 0){
            int reply = JOptionPane.showConfirmDialog(this, RBUtils.getBoundle("returnConfirm"), RBUtils.getBoundle("returnConfirm.title"), JOptionPane.YES_NO_OPTION, JOptionPane.WARNING_MESSAGE);
            if (reply == JOptionPane.YES_OPTION) {
            Integer row = borrowedMediumsTable.getSelectedRow();
            Medium medium = mediumModel.getValueAt(row);                       
        
            borrowManager.returnBorrow(medium);  
            mediumModel.deleteValue(medium);      
            }
        }   
    }//GEN-LAST:event_jButton2ActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                ShowBorrowsDialog dialog = new ShowBorrowsDialog(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {              
                    
                    
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable borrowedMediumsTable;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JLabel textLabel;
    // End of variables declaration//GEN-END:variables
}
